﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;

namespace QuanLyThuNgan
{
    public partial class frm_TraLaiThuoc : DevExpress.XtraEditors.XtraForm
    {
        public frm_TraLaiThuoc()
        {
            InitializeComponent();
        }
        DonVi_Khac dv_khac = new DonVi_Khac();
        DataTable dtkhoitao = new DataTable();
        DataTable dtThuoc = new DataTable();
        ThuocNoiTruMstCTL tntmstctl = new ThuocNoiTruMstCTL();
        int machung; public DataTable _dvd = new DataTable();
        public BenhNhanInfo bninfo = new BenhNhanInfo();
        public BenhNhanInfo Bninfo
        {
            get { return bninfo; }
            set { bninfo = value; }
        }
      
        private void frm_RaToaThuoc_Load(object sender, EventArgs e)
        {
            LoadFrom();
            LoadDSPhieu();
        }
        public void DatatableKhoitao()
        {
            DataTable dtkhoitao = new DataTable();
            dtkhoitao.Columns.Add("bdid", typeof(int));
            dtkhoitao.Columns.Add("dvt", typeof(string));
            dtkhoitao.Columns.Add("slg", typeof(int));
            dtkhoitao.Columns.Add("dongia", typeof(int));
            dtkhoitao.Columns.Add("Slgsdao", typeof(float));
            dtkhoitao.Columns.Add("slgtra", typeof(float));
            dtkhoitao.Columns.Add("tdgtra", typeof(int));
            dtkhoitao.Columns.Add("thanhtien", typeof(int));
            dtkhoitao.Columns.Add("sobn", typeof(string));
            gridControl_thuoc.DataSource = dtkhoitao;
        }
        public DataTable m_DataTable(string _ma, string _ten, string giatri_ten1, string giatri_ten2)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn(_ma, typeof(string)));
            dt.Columns.Add(new DataColumn(_ten, typeof(string)));
            DataRow dr = dt.NewRow();
            DataRow dr3 = dt.NewRow();
            dr3[_ma] = "1";
            dr3[_ten] = giatri_ten1;
            dt.Rows.Add(dr3);
            dr[_ma] = "2";
            dr[_ten] = giatri_ten2;
            dt.Rows.Add(dr);

            return dt;
        }
        public void m_gridView_CellValueChanged(GridView _g, DataRow dow, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int currentCol = e.Column.VisibleIndex;
            DataRow dr = _g.GetDataRow(_g.FocusedRowHandle);
            if (currentCol == _g.Columns["slgtra"].VisibleIndex )
            {
                if (dr["Slgsdao"] != null)
                {
                    if (float.Parse(dr["slgtra"].ToString()) <= float.Parse(dr["Slgsdao"].ToString()) && float.Parse(dr["slgtra"].ToString()) > 0)
                    {
                        float soluong = float.Parse(dr["slgtra"].ToString() == "" ? "1" : dr["slgtra"].ToString());
                        if (dr["dongia"] != null)
                            dr["tdgtra"] = soluong * float.Parse(dr["dongia"].ToString());
                    }
                    else
                        XtraMessageBox.Show("Số lượng trả không hợp lý","Thông báo");

                }
            }

          
        }
        void  LoadFrom()
        {
            DataTable dtBS = dv_khac.DMBacSi();
            ClassHelp.m_SearchLookUpEdit(dtBS, scboBS, "TenBS", "IDBS");
            dtDenNgay.EditValue = Uit.it_Date.CurrentDate2();
            dt_TuNgay.EditValue = Uit.it_Date.CurrentDate2();
            DatatableKhoitao();
            DataTable dtNoi= dv_khac.DonVi_Pharma();
            foreach (DataRow dr in dtNoi.Rows)
            {
                dr["tendv"] = Uit.it_Font.VNIToUnicode(dr["tendv"].ToString());
            }
          //  DataTable dt_buoidung = m_DataTable("idtgdung", "tgdung", "Trước ăn", "Sau ăn");
            DataSet dsload = dv_khac.Load_All_DanhMuc_ToaThuoc();
            dtThuoc = dsload.Tables[0];
            ClassHelp.m_LookUpEdit(dtNoi, cbo_noigiaothuoc, "tendv", "madv");
            ClassHelp.m_RepositoryItenSearchLookUpEdit(dsload.Tables[0], rpscbo_thuoc, "tenbd", "bdid");
            _dvd= dv_khac.LayDSDVD();
            txthoten.Text = bninfo.Ten;
            txtGioiTinh.Text = bninfo.Gioi;
            txtsonhapvien.Text = bninfo.SoNhapVien;
            txttuoi.Text = bninfo.Tuoi.ToString();
            txtDiaChi.Text = bninfo.DiaChi;
            txtngaylanh.Text = Uit.it_Date.CurrentDate("dd/MM/yyyy");
            txtthang.Text = Uit.it_Date.CurrentDate("MM-yyyy");
            cbo_noigiaothuoc.EditValue = "K1";
            if (bninfo.Bhytxv && bninfo.Ngaybhyt == "")
                radioGroup1.SelectedIndex = 1;
            else
                radioGroup1.SelectedIndex = 0;
            DataTable dtldo = dv_khac.LyDoTraThuoc();
            foreach (DataRow dro in dtldo.Rows)
            {
                dro["tenlydotra"] = Uit.it_Font.VNIToUnicode(dro["tenlydotra"].ToString());
            }
            ClassHelp.m_SearchLookUpEdit(dtldo, scboLyDoTra, "tenlydotra", "idlydotra");
            if(txtsophieu.Text !="")
            gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
           
        }
        private void gridView_thuoc_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle < 0) e.Info.DisplayText = "";
                else e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
            else { e.Info.DisplayText = "STT"; }
            e.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
        }

        private void gridView_thuoc_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int currentCol = e.Column.VisibleIndex;
            DataRow dr = gridView_thuoc.GetDataRow(gridView_thuoc.FocusedRowHandle);
             machung =Uit.it_Parse.ToInteger(dr["bdid"]);
            if (machung > 0)
            {
               
                m_gridView_CellValueChanged(gridView_thuoc, dr, e);
            }
        }
      
        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (IsValidToa())
            {
                LuuToaThuoc();
            }
        }
        bool IsValidToa()
        {
           
            if (cbo_noigiaothuoc.EditValue == null)
            {
                XtraMessageBox.Show("Chưa chọn nơi giao thuốc","Thông Báo");
                return false;
            }
            if (scboLyDoTra.Text == "")
            {
                XtraMessageBox.Show("Chưa chọn lý do trả thuốc", "Thông Báo");
                return false;
            }
            // benh nhan da xuat vien
            if (tntmstctl.m_KiemTraXuatVien(bninfo.SoNhapVien) == null)
            {
                //XtraMessageBox.Show("Bệnh Nhân đã xuất viện", "Thông Báo");
               // return false;
            }
            if (bool.Parse(tntmstctl.m_KiemTraTraThuoc(txtsophieu.Text).ToString()) == true)
            {
                //XtraMessageBox.Show("Thuốc đã quá giới hạn trả", "Thông Báo");
                // return false;
            }
            if (txtsonhapvien.Text == "")
            {
                XtraMessageBox.Show("Chưa chọn bệnh nhân");
                return false;
            }
            //Kiem tra con bsi cghi dinh 
            if (scboBS.EditValue == null || txtChuanDoan.Text=="")
            {
                XtraMessageBox.Show("Chưa chọn Bác Sĩ hoặc Chuẩn đoán", "Thông Báo");
                return false;
            }

            //quyen sua toa thuoc
            //if (TOA_ChiBoSung)
            //{
            //    MessageBox.Show("Khong sua duoc Toa qua ngay/ Toa cua bac si khac!");
            //    return false;
            //}
            //string ThongBao;
            //if (LaNgayNghi(out ThongBao))
            //{
            //    MessageBox.Show(ThongBao);
            //    return false;
            //}
            return true;
        }
        void LuuToaThuoc()
        {
            string _sqltntmst = "",_sqldtl="";
            if (gridView_thuoc.RowCount == 1 )
            {
                XtraMessageBox.Show("Lưu toa thất bại");
                return;
            }
            ThuocNoiTruMstDTO tntmstdto = new ThuocNoiTruMstDTO();
            ThuocNoiTruCTL tntctl = new ThuocNoiTruCTL();
            ThuocNoiTruMstCTL tntmstctl = new ThuocNoiTruMstCTL();
            tntmstdto.Sobn = txtsophieu.Text;
            tntmstdto.SoNhapvien1 = txtsonhapvien.Text;
            tntmstdto.Idbstrathuoc = Uit.it_Parse.ToInteger(scboBS.EditValue);
            tntmstdto.Idlydotra = Uit.it_Parse.ToInteger(scboLyDoTra.EditValue);
            tntmstdto.Idnguoinhap = frmLogin.nd.IDNguoiDung;
            tntmstdto.Tientra = Uit.it_Parse.ToInteger(gridColumn_dgTra.SummaryItem.SummaryValue);
            //so tien con lai
            tntmstdto.Sotien = Uit.it_Parse.ToInteger(gridColumn_ThanhTien.SummaryItem.SummaryValue) -tntmstdto.Tientra ;
            for (int i = 0; i < gridView_thuoc.RowCount-1; i++)
            {
                ThuocNoiTruDTO tntdto = new ThuocNoiTruDTO();
                DataRow dr = gridView_thuoc.GetDataRow(i);
                tntdto.Bdid = Uit.it_Parse.ToInteger(dr["bdid"]); 
                tntdto.Slgtra = float.Parse(dr["slgtra"].ToString());
                tntdto.Slgcosan = float.Parse(dr["slgcosan"].ToString() == "" ? "0" : dr["slgcosan"].ToString());
                tntdto.Dgtra = Uit.it_Parse.ToInteger(dr["dongia"]);
                tntdto.Trigia = float.Parse(tntdto.Slgtra.ToString()) * float.Parse(tntdto.Dgtra.ToString());
                tntdto.Slgsd = float.Parse(dr["Slgsdao"].ToString() == "" ? "0" : dr["Slgsdao"].ToString()) - tntdto.Slgtra;
                _sqldtl = _sqldtl + " "+ tntctl.m_Update_TraThuoc(tntmstdto.Sobn,tntdto.Bdid,tntdto.Slgtra,tntdto.Dgtra,tntdto.Slgsd);
            }
             FeentMstCTL feentmstctl= new FeentMstCTL();
            _sqltntmst = _sqltntmst + " " + tntmstctl.m_Update_TraThuoc(tntmstdto.Sobn, tntmstdto.SoNhapvien1, tntmstdto.Tientra, tntmstdto.Idlydotra, tntmstdto.Idnguoinhap, tntmstdto.Idbstrathuoc);
            _sqltntmst = _sqltntmst + " " + feentmstctl.m_Update_TraThuoc(tntmstdto.Sobn,Uit.it_Parse.ToDecimal(tntmstdto.Sotien,false));
            if (Uit.it_SQL.ExecuteNonQuery(_sqltntmst +_sqldtl))
            {
                gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
                XtraMessageBox.Show("Lưu thành công");
            }
            else
                XtraMessageBox.Show("Lưu toa thất bại");
        }
        // tap danh sach toa thuoc
        void LoadDSPhieu()
        {
            dtDenNgay_DS.EditValue = Uit.it_Date.CurrentDate2();
            dtTuNgay_DS.Properties.MaxValue = Uit.it_Date.CurrentDate2();
            DateTime dtmin = new DateTime(dtDenNgay_DS.DateTime.Year, dtDenNgay_DS.DateTime.Month-1, 1);
            dtTuNgay_DS.Properties.MinValue = dtmin;
            dtTuNgay_DS.EditValue = Uit.it_Date.CurrentDate2();
            dtDenNgay_DS.Properties.MinValue = dtmin;
        }
        string sTenSearch = "";
        string sColSearch ;
        private void OpenTap(string NameTap)
        {
            for (int i = 0; i < xtraTabControl1.TabPages.Count; i++)
            {
                if (xtraTabControl1.TabPages[i].Name.Equals(NameTap))
                {
                    xtraTabControl1.TabPages[i].PageEnabled = true;
                    // xtraTabControlChiPhiNGTru.TabPages[i].Focus();
                }
                else
                    xtraTabControl1.TabPages[i].PageEnabled = false;
            }
        }
        DataTable dttk = new DataTable();
        private void gridView_DS_ColumnFilterChanged(object sender, EventArgs e)
        {
            ColumnView view = sender as ColumnView;
            view.ActiveFilter.Add(view.Columns[sColSearch], new ColumnFilterInfo("[" + sColSearch + "] Like '%" + sTenSearch + "%'", ""));

        }
        private void gridView_DS_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            sTenSearch = e.Value.ToString();
            sColSearch = e.Column.FieldName;
        }
        private void btnTimKiem_DS_Click(object sender, EventArgs e)
        {
            dttk = dv_khac.DanhSachToaThuoc(dtTuNgay_DS.DateTime.ToString("MM/dd/yyyy"), dtDenNgay_DS.DateTime.ToString("MM/dd/yyyy"), frmLogin.nd.MaDonVi);
            gridControl1.DataSource = dttk;

        }

        private void gridView_DS_DoubleClick(object sender, EventArgs e)
        {
            DataRow dr = gridView_DS.GetDataRow(gridView_DS.FocusedRowHandle);
            if (dr == null) return;
            DataView dtvtk = dttk.DefaultView;
            dtvtk.Sort = "sobn";
            bninfo.Coratoa = true;
            int id_dt = dtvtk.Find(gridView_DS.GetRowCellValue(gridView_DS.FocusedRowHandle, gridColumn_sobn).ToString());
            bninfo.Ten=dtvtk[id_dt]["tenbn"].ToString();
            bninfo.Gioi = dtvtk[id_dt]["GioiTinh"].ToString();
            bninfo.NamSinh = Uit.it_Parse.ToInteger(dtvtk[id_dt]["NamSinh"]);
            bninfo.Tuoi = Uit.it_Parse.ToInteger(dtvtk[id_dt]["tuoi"]);
			bninfo.DiaChi = dtvtk[id_dt]["DiaChi"].ToString();
            txtsophieu.Text= dtvtk[id_dt]["sobn"].ToString();
            txthoten.Text = bninfo.Ten;
            txtGioiTinh.Text =bninfo.Gioi;
            txtsonhapvien.Text = dtvtk[id_dt]["sonhapvien"].ToString();
            txttuoi.Text = bninfo.Tuoi.ToString();
            txtDiaChi.Text = bninfo.DiaChi;
            txtngaylanh.Text =Uit.it_Parse.ToDateTime(dtvtk[id_dt]["ngay"],"dd/MM/yyyy").ToString();
            cbo_noigiaothuoc.EditValue = dtvtk[id_dt]["makho"];
            txtChuanDoan.Text = dtvtk[id_dt]["chandoan"].ToString();
            dtDenNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["denngay"]);
            dt_TuNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["tungay"]);
            scboBS.EditValue= dtvtk[id_dt]["idbacsi"];
            txtthang.Text = dtvtk[id_dt]["yymm"].ToString().Substring(2, 2) + "-" + dtvtk[id_dt]["yymm"].ToString().Substring(0, 2);
            //t.xacnhan,,,t.sohs,t.sotien,t.,t.madvpk,t.idnguoinhap,t.toaxv
            bninfo.MaSo = dtvtk[id_dt]["sohs"].ToString();
            gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
            DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(dtvtk[id_dt]["sohs"].ToString());
            bool brealo = true;
            if (dtkt.Rows[0]["traibenh"].ToString() != dtvtk[id_dt]["madvpk"].ToString())
                brealo = false;
            if(dtkt.Rows[0]["xuatvien"].ToString() !="")
                brealo = false;
            if(dtkt.Rows[0]["bhytset"].ToString() =="True" && dtkt.Rows[0]["ngaybhyt"].ToString()=="" )
                radioGroup1.SelectedIndex = 1;
            else
                radioGroup1.SelectedIndex = 0;
            //if (brealo == false)
            //    gridView_thuoc.OptionsBehavior.ReadOnly = true;
            //else
            //    gridView_thuoc.OptionsBehavior.ReadOnly = false;
            OpenTap(xtraTabPage1.Name);
                
        }
       
        private void gridView_DS_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                DataRow dr = gridView_DS.GetDataRow(gridView_DS.FocusedRowHandle);
                if (dr == null) return;
                DataView dtvtk = dttk.DefaultView;
                dtvtk.Sort = "sobn";
                bninfo.Coratoa = true;
                int id_dt = dtvtk.Find(gridView_DS.GetRowCellValue(gridView_DS.FocusedRowHandle, gridColumn_sobn).ToString());
                bninfo.Ten = dtvtk[id_dt]["tenbn"].ToString();
                bninfo.Gioi = dtvtk[id_dt]["GioiTinh"].ToString();
                bninfo.NamSinh = Uit.it_Parse.ToInteger(dtvtk[id_dt]["NamSinh"]);
                bninfo.Tuoi = Uit.it_Parse.ToInteger(dtvtk[id_dt]["tuoi"]);
                bninfo.DiaChi = dtvtk[id_dt]["DiaChi"].ToString();
                txtsophieu.Text = dtvtk[id_dt]["sobn"].ToString();
                txthoten.Text = bninfo.Ten;
                txtGioiTinh.Text = bninfo.Gioi;
                txtsonhapvien.Text = dtvtk[id_dt]["sonhapvien"].ToString();
                txttuoi.Text = bninfo.Tuoi.ToString();
                txtDiaChi.Text = bninfo.DiaChi;
                txtngaylanh.Text = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["ngay"], "dd/MM/yyyy").ToString();
                cbo_noigiaothuoc.EditValue = dtvtk[id_dt]["makho"];
                txtChuanDoan.Text = dtvtk[id_dt]["chandoan"].ToString();
                dtDenNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["denngay"]);
                dt_TuNgay.EditValue = Uit.it_Parse.ToDateTime(dtvtk[id_dt]["tungay"]);
                scboBS.EditValue = dtvtk[id_dt]["idbacsi"];
                txtthang.Text = dtvtk[id_dt]["yymm"].ToString().Substring(2, 2) + "-" + dtvtk[id_dt]["yymm"].ToString().Substring(0, 2);
                //t.xacnhan,,,t.sohs,t.sotien,t.,t.madvpk,t.idnguoinhap,t.toaxv
                bninfo.MaSo = dtvtk[id_dt]["sohs"].ToString();
                gridControl_thuoc.DataSource = dv_khac.ToaThuoc_ChiTiet(txtsophieu.Text);
                DataTable dtkt = dv_khac.NhapVien_ToaThuoc_ChiTiet(dtvtk[id_dt]["sohs"].ToString());
                bool brealo = true;
                if (dtkt.Rows[0]["traibenh"].ToString() != dtvtk[id_dt]["madvpk"].ToString())
                    brealo = false;
                if (dtkt.Rows[0]["xuatvien"].ToString() != "")
                    brealo = false;
                if (dtkt.Rows[0]["bhytset"].ToString() == "True" && dtkt.Rows[0]["ngaybhyt"].ToString() == "")
                    radioGroup1.SelectedIndex = 1;
                else
                    radioGroup1.SelectedIndex = 0;
                //if (brealo == false)
                //    gridView_thuoc.OptionsBehavior.ReadOnly = true;
                //else
                //    gridView_thuoc.OptionsBehavior.ReadOnly = false;
                OpenTap(xtraTabPage1.Name);
            }
        }

        private void btndsphieu_Click(object sender, EventArgs e)
        {
            OpenTap(xtraTabPage2.Name);
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }


       
    }
}